package com.shujia.mr.hw.home1;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Home1Reducer extends Reducer<Text, Text, NullWritable, Student> {

    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, NullWritable, Student>.Context context) throws IOException, InterruptedException {
        Student student = new Student();
        student.setStudentID(key.toString());
        int totalScore = 0;

        List<String> objectAndScores = new ArrayList<>();

        // 结果有两类数据，基本信息和学生各科成绩
        for (Text value : values) {
            String oneValue = value.toString();
            String[] columns = oneValue.split(",");
            if (columns.length == 2) {
                // 学生各科成绩
                /**
                 * columns:
                 * 1000001,98
                 * 1000002,5
                 * 1000003,137
                 * 1000004,29
                 * 1000005,85
                 * 1000006,52
                 */
                totalScore += Integer.parseInt(columns[1]);
                // 由于values是一个迭代器，需要将各科成绩用Java中List进行保存
                objectAndScores.add(oneValue);

            } else {
                // 基本信息 (施笑槐,22,女,文科六班)
                student.setName(columns[0]);
                student.setAge(columns[1]);
                student.setGender(columns[2]);
                student.setClazz(columns[3]);
            }
        }

        // 循环获取所有数据后，可以对总分进行判断
        if (totalScore > 450) {
            student.setTotalScore(Integer.toString(totalScore));
            for (String objectAndScore : objectAndScores) {
                String[] objectAndScoreSplit = objectAndScore.split(",");
                student.setObjectID(objectAndScoreSplit[0]);
                student.setScore(objectAndScoreSplit[1]);
                context.write(NullWritable.get(),student);
            }
        }

    }
}
